<template>
  <el-card class="box-card">
    <div class="model-role">
      <el-form :inline="true" :model="dataForm" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="dataForm.roleName" clearable placeholder="区域名称"></el-input>
        </el-form-item>
        <el-form-item><el-button @click="getDateList">查询</el-button></el-form-item>
        <el-form-item><el-button type="primary" @click="openDialog()">添加区域</el-button></el-form-item>
      </el-form>
      <el-table :data="dataList" border style="width: 100%">
        <el-table-column prop="area" label="地区" width="300"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="300"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[5,10,20]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total,sizes,prev,pager,next,jumper"
        style="margin-top: 30px">
      </el-pagination>
    </div>

    <el-dialog :title="dataDialogForm.id === '' ?  dialogTitle:dialogTitle='更新区域信息' " :visible.sync="dialogFormVisible" @close="closeDialog()">
      <el-form :model="dataDialogForm" :rules="rules" ref="ruleForm">
        <el-form-item label="区域名称" :label-width="formLabelWidth" prop="role_name">
          <el-input v-model="dataDialogForm.area" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm()">确 定</el-button>
      </div>
    </el-dialog>

  </el-card>
</template>

<script>

export default {
  name: 'customer',
  data() {
    var checkUserNameIsExists = (rule,value,callback) => {
      if(value === ''){
        callback(new Error('请输入用户名'))
      }else{
        //调用后端接口  检查是否存在
        this.$http.get('/user/username='+value).then((res)=>{
          console.log(res)
          if(res.data.data != ''){
            callback(new Error('该用户已存在'))
          }
        })
        callback()
      }
    };
    return {
      dialogTitle: '添加区域',
      dataForm:{
        roleName: "",
      },
      ruleForm:{
        pass: '',
      },
      dataDialogForm:{
        id: '',
        area:'',
        createUser:'',
        updateUser:'',
        createTime:''

      },
      dataList:[],
      userName: "xiaohei",
      pageIndex: 1,
      pageSize:5,
      totalPage:0,
      datalistLoading:false ,
      dialogFormVisible:false,
      dialogFormSubmitVisible:false,
      formLabelWidth: '120px',
      rules:{
        username:[{required:true ,message:'请输入用户名',trigger:'blur'},{validator:checkUserNameIsExists,trigger: 'blur'}],
        password:[{required:true ,message:'请输入密码',trigger:'blur'},
          {min:8, message: "密码至少为8位", trigger: 'blur'},//密码校验
          {pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,}$/, message: '密码必须包含至少8位，且有数字、字母和特殊符号'}],
        phone:[{required:true ,message:'请输手机号',trigger:'blur'},{pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号'},]
      }
    };
  },
  methods:{
    getToken(){
      console.log(sessionStorage.getItem("token"))
      return sessionStorage.getItem("token")
    },
    async fetchData(){
      try{
        const token = this.getToken();
        if(!token){
          this.$router.push("/login");
        }
      }catch (error){
        console.error(error)
      }
    },
    sizeChangeHandle(val){
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDateList()
    },
    currentChangeHandle(val){
      this.pageIndex = val
      this.getDateList()
    },
    getDateList(){
      // this.datalistLoading = true
      //生命params 分页查询的参数
      const params = {
        params:{
          pageIndex:this.pageIndex,
          pageSize:this.pageSize,
          area:this.dataForm.area
        }
      }
      this.$http.get('/region/findByPage',params
      ).then((res)=>{
        this.dataList = res.data.data.records
      })
    },
    handleEdit(index,item){
      //打开更新窗口
      this.dialogFormVisible = true
      this.dataDialogForm.id = item.id
      this.dataDialogForm.area = item.area
      this.dataDialogForm.updateUser = item.updateUser
      this.dataDialogForm.createUser = item.createUser
      console.log('item',item)
    },
    handleDelete(index, item){
      this.$confirm('此操作将永久删除该区域信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete('/region/'+item.id).then((res)=>{
          console.log(item.id)
          this.dataDialogForm.id = item.id
          if(res.data.code != 200) {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          } else {
            this.getDateList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }
          
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //添加用户按钮绑定的方法
    openDialog(){
      //打开窗口
      this.dialogFormVisible = true
    },
    closeDialog(){
      //关闭窗口
      //清空表单
      this.dialogTitle = '添加区域';
      this.dialogFormVisible = false
      this.dataDialogForm.id = ''
      this.dataDialogForm.area = ''
      this.dataDialogForm.createUser = ''
      this.dataDialogForm.updateUser = ''
    },
    handleConfirm() {
      // 当点击确定按钮时，访问当前对话框的标题
      const title = this.dialogTitle;
      console.log('当前对话框标题:', title);

      // 根据标题执行不同的逻辑
      if (title === '添加区域') {
        this.handleSubmitFormData('ruleForm');
      } else if (title === '更新区域信息') {
        this.handleUpdateFormData('ruleForm');
      }

      // 可以在这里添加其他需要的逻辑
    },
    handleSubmitFormData(ruleForm){
      //打开窗口
      // this.dialogFormVisible = true
      this.addRegion(ruleForm)
    } ,
    handleUpdateFormData(ruleForm){
      this.updateRegion(ruleForm)
    },
    updateRegion(ruleForm){
      this.$refs[ruleForm].validate((valid) => {
        this.$http.put('/region',this.dataDialogForm).then((res)=>{
          console.log(res)
          this.dialogFormVisible = false   //关闭窗口
          this.closeDialog()
          this.getDateList()
        })
      });
    },
    addRegion(ruleForm){
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
            this.dialogFormSubmitVisible= true;
            this.$http.post('/region',this.dataDialogForm).then((res)=>{
              console.log(res)
              this.dialogFormVisible = false   //关闭窗口
              this.closeDialog()
              this.getDateList()
            })
            this.dialogFormVisible = false
            this.dialogFormSubmitVisible= false
            return
        } else {
          return false;
        }
      });
    }
  },
  mounted() {
    this.getDateList()
  },
}

</script>

